import { tryOnDocumentLoaded } from 'shared/utils/utils'
import tpl from '../assets/dialog-message.html?raw'

interface Stop {
  (): void
  fragment: HTMLDivElement
}

export interface MessageOptions {
  message: string
  type?: 'success' | 'error' | 'info' | 'warn'
  timeout?: number
}

let fragment: HTMLDivElement | null = null

export function showMessage(options: MessageOptions) {
  fragment?.remove()

  const { type, message, timeout } = options

  fragment = document.createElement('div')
  fragment.innerHTML = tpl.replace('{message}', message).replace('{type}', type ?? 'info')

  tryOnDocumentLoaded(() => {
    fragment && document.body.append(fragment)
  })

  const stop: Stop = () => {
    if (fragment === stop.fragment) {
      fragment.remove()
      fragment = null
    }
  }

  stop.fragment = fragment

  timeout !== 0 && setTimeout(stop, timeout || 3000)

  return stop
}
